import { handleActions as createReducer } from 'redux-actions'
import {
    saveCarts,
    addProductToLocalCart,
    changeLocalProductNumber,
    deleteProductFromLocalCart,
} from "../actions/cart.action"

const initialSata = []

// 将商品添加到本地购物车数据中
const handleAddProductToLocalCart = (state, action) => {
    // 如果购物车中 之前没有该商品 就直接添加
    // 如果购物车中之前有该商品 那么将购物车中商品数量 + 1

    // 拷贝一份选中的商品数据
    const newState = JSON.parse(JSON.stringify(state))

    let product = newState.find(product => product.id === action.payload.id)

    if (product) {
        // 之前购物车中有该商品
        product.count = product.count + 1
    } else {
        // 之前购物车里没有数据，将新的数据添加到store当中
        newState.push(action.payload)
    }
    return newState
}

const handleSaveCarts = (state, action) => action.payload

const handleDeleteProductFromLocalCart = (state, action) => {
    const newState = JSON.parse(JSON.stringify(state))
    let newData = newState.filter(product => product.id !== action.payload)
    return newData
}

const handleChangeLocalProductNumber = (state, action) => {
    const newState = JSON.parse(JSON.stringify(state))
    let product = newState.find(product => product.id === action.payload.id)
    product.count = action.payload.count

    return newState
}


export default createReducer({
    // 将商品添加到本地的购物车数据中
    [addProductToLocalCart]: handleAddProductToLocalCart,
    [saveCarts]: handleSaveCarts,
    [deleteProductFromLocalCart]: handleDeleteProductFromLocalCart,
    [changeLocalProductNumber]: handleChangeLocalProductNumber
}, initialSata)